package cn.fintecher.pangolin.common.utils;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:17 2019/11/1
 */
public class RepositoryUtil {
    /**
     * 保存ES数据
     */
    public static <T> void saveData(ElasticsearchRepository<T, String> repository, List<T> list) {
        if (list.isEmpty()) {
            return;
        }
        if (list.size() <= 10000) {
            repository.saveAll(list);
        } else {
            int flag = (int) Math.ceil((double) list.size() / 10000);
            for (int i = 0; i < flag; i++) {
                Pageable pageable = PageRequest.of(i, 10000);
                List<T> list1 = list.stream().skip(pageable.getPageNumber() * pageable.getPageSize()).limit(pageable.getPageSize()).collect(Collectors.toList());
                repository.saveAll(list1);
            }
        }
    }

    /**
     * 保存mysql数据
     */
    public static <T> void saveData(JpaRepository<T, String> repository, List<T> list) {
        if (list.isEmpty()) {
            return;
        }
        if (list.size() <= 10000) {
            repository.saveAll(list);
        } else {
            int flag = (int) Math.ceil((double) list.size() / 10000);
            for (int i = 0; i < flag; i++) {
                Pageable pageable = PageRequest.of(i, 10000);
                List<T> list1 = list.stream().skip(pageable.getPageNumber() * pageable.getPageSize()).limit(pageable.getPageSize()).collect(Collectors.toList());
                repository.saveAll(list1);
            }
        }
    }

    /**
     * 删除ES数据
     */
    public static <T> void deleteData(ElasticsearchRepository<T, String> repository, BoolQueryBuilder builder) {
        Iterable<T> iterable = repository.search(builder);
        if (iterable.iterator().hasNext()) {
            repository.deleteAll(iterable);
        }
    }
}
